package com.byCreatetion.adabter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import com.byCreation.Control.Control;
import com.byCreation.t_globe.CardActivity;
import com.byCreation.t_globe.CardDetailActivity;
import com.byCreation.t_globe.ContentActivity;
import com.byCreation.t_globe.MapActivity;
import com.byCreation.t_globe.R;
import com.google.android.gms.maps.model.LatLng;
import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.core.decode.BaseImageDecoder;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.squareup.picasso.Picasso;





import Myclass.AllIntent;
import Myclass.ConnectInternet;
import Parser.HttpGetJson;
import Parser.SendToBD;
import YouTubeApi.CallYouTubeApi;

import android.R.integer;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.AsyncTask;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;




public class CardListAdapter extends BaseAdapter {
    
	
    private Context activity;
    private LayoutInflater inflater=null;
  //  public ImageLoader imageLoader; 
  
    ArrayList<HashMap<String, Object>> MyArrList = new ArrayList<HashMap<String, Object>>();
    
    
     private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
	 private ImageLoader imageLoader = ImageLoader.getInstance();
	 private DisplayImageOptions options;
	 
	 
	 
	 private String[] ColorCat={"#e9798c","#548ed3","#5cb4d3","#76b979","#e9798c","#548ed3","#5cb4d3","#76b979","#5cb4d3","#e9798c"};
	 private String[] NameCat={
			 "activities"
			 ,"attractions"
			 ,"entertainment"
			 ,"events"
			 ,"other_services"
			 ,"real_estate"
			 ,"restaurants"
			 ,"services"
			 ,"shops"
			 ,"accommodation"};
	 
	// accommodation
	 
	 private AllIntent allintent;
	 
	
    
    public CardListAdapter(Activity a,ArrayList al ) {
    	
    	activity = a;
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        MyArrList=al;
       
    
    
        options = new DisplayImageOptions.Builder()
		.showStubImage(R.drawable.ic_launcher)
		.showImageForEmptyUri(R.drawable.ic_launcher)
		.showImageOnFail(R.drawable.ic_launcher)
		.delayBeforeLoading(100)
	        .cacheInMemory()
			.cacheOnDisc()
			.bitmapConfig(Bitmap.Config.RGB_565)
		.build();
	initImageLoader(activity.getApplicationContext());
	
	allintent=new AllIntent(activity);
    
    }
    
    public  String card_id,title="";
    private class ViewHolder {
    	private TextView txt_cat,title,subscriberCount,updated,txt_newvdo,title2,subscriberCount2,txt_content;
		private ImageView img_sponser,thumbnail,img_more,img_more_hide,img_bookmark,img_addbookmark,img_call,img_compare,img_map,img_web;
		private FrameLayout lay_detail,laycat_color,laycat_color2;
		private RatingBar ratingBar1;
    }


   
    @Override
	public int getCount() {
        return MyArrList.size();
    }
    @Override
    public Object getItem(int position) {
        return position;
    }
    @Override
    public long getItemId(int position) {
        return position;
    }
    
    public View getView(final int position, View convertView, ViewGroup parent) {
      
    	View vi=convertView;
    	final ViewHolder holder;
    	final Animation anim_in = AnimationUtils.loadAnimation(activity, R.anim.anim_listcard_in);
    	final Animation anim_out = AnimationUtils.loadAnimation(activity, R.anim.anim_listcard_out);
    	
    	
        if(convertView==null)
        {
	        vi = inflater.inflate(R.layout.item_card_listview, null);
	        holder = new ViewHolder();
		    holder.thumbnail = (ImageView)vi.findViewById(R.id.img_list);
		    holder.title = (TextView)vi.findViewById(R.id.txt_title);
		    holder.subscriberCount= (TextView)vi.findViewById(R.id.txt_subscriberCount);
		    
		    holder.title2 = (TextView)vi.findViewById(R.id.txt_title2);
		    holder.subscriberCount2= (TextView)vi.findViewById(R.id.txt_subscriberCount2);
		    
		    holder.txt_content= (TextView)vi.findViewById(R.id.txt_content);
		    
		    holder.img_more= (ImageView)vi.findViewById(R.id.img_more);
		    holder.lay_detail=(FrameLayout)vi.findViewById(R.id.lay_detail);
		    holder.img_more_hide=(ImageView)vi.findViewById(R.id.img_more_hide);
		    
		    holder.img_bookmark=(ImageView)vi.findViewById(R.id.img_bookmark);
		    holder.txt_cat= (TextView)vi.findViewById(R.id.txt_cat);
		    holder.laycat_color=(FrameLayout)vi.findViewById(R.id.laycat_color);
		    holder.laycat_color2=(FrameLayout)vi.findViewById(R.id.laycat_color2);
		    
		    
		    //menu
		    holder.img_addbookmark=(ImageView)vi.findViewById(R.id.img_addbookmark);
		    holder.img_call=(ImageView)vi.findViewById(R.id.img_call);
		    holder.img_compare=(ImageView)vi.findViewById(R.id.img_compare);
		    holder.img_map=(ImageView)vi.findViewById(R.id.img_map);
		    holder.img_web=(ImageView)vi.findViewById(R.id.img_web);
		    
		    holder.img_sponser=(ImageView)vi.findViewById(R.id.img_sponser);
		    holder.ratingBar1=(RatingBar)vi.findViewById(R.id.ratingBar1);
		    
		    
			vi.setTag(holder);	
			
			
	 	
	 		
	 	
	 		
	}else 
    {
		  
    		holder = (ViewHolder)vi.getTag();
    }
            
        //=================================SetData===================================   
     
        
        
        try{  
        	
          holder.ratingBar1.setRating(Integer.parseInt(MyArrList.get(position).get("rating5").toString()));
      	Log.e("TG", "rating5:"+Integer.parseInt(MyArrList.get(position).get("rating5").toString()));

          
          
         holder.img_more.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
            	holder.lay_detail.setVisibility(View.VISIBLE);
            	holder.lay_detail.startAnimation(anim_in);
            	Log.e("TG", "Click More");
            	Control.Cardlist_ShowDetail.set(position, true);
            }

        });
         
         holder.img_more_hide.setOnClickListener(new OnClickListener() {

             @Override
             public void onClick(View v) {
                 // TODO Auto-generated method stub
             	holder.lay_detail.setVisibility(View.INVISIBLE);
             	holder.lay_detail.startAnimation(anim_out);
             	Log.e("TG", "Click More");
             	Control.Cardlist_ShowDetail.set(position, false);
             }

         });
         
         
         
         //========Chk_card
         if(Control.Cardlist_ShowDetail.get(position))
         {
        	 holder.lay_detail.setVisibility(View.VISIBLE);
         }
         else
        	 holder.lay_detail.setVisibility(View.INVISIBLE);
         
        
         
        
         
         
        	
		
	        
         holder.title.setText(MyArrList.get(position).get("name").toString());
         holder.subscriberCount.setText(MyArrList.get(position).get("name2").toString());
      
         holder.title2.setText(MyArrList.get(position).get("name").toString());
         holder.subscriberCount2.setText(MyArrList.get(position).get("name2").toString());
         holder.txt_content.setText(MyArrList.get(position).get("card_desc").toString());
	
         Log.e("TG", "get img="+MyArrList.get(position).get("img").toString());
	        Picasso.with(activity).load("http://"+MyArrList.get(position).get("img").toString()).into(holder.thumbnail);
	
	        //if(!MyArrList.get(position).get("img").toString().equals(""))
	       // try {imageLoader.displayImage("http://"+MyArrList.get(position).get("img").toString(), holder.thumbnail, options, animateFirstListener);}catch (Exception e) {e.printStackTrace();}
	        
	        if(Boolean.valueOf(MyArrList.get(position).get("sponsortype").toString()))
	        {
		        Log.e("tglobe", "sponsortype:"+(Boolean) MyArrList.get(position).get("sponsortype")+"Name:"+MyArrList.get(position).get("name").toString());
	        	holder.img_sponser.setVisibility(View.VISIBLE);
	        	
	        }
	        else
	        	holder.img_sponser.setVisibility(View.INVISIBLE);

	       
	        
	        int i=0;
	        while(i<NameCat.length)
	        {
	        	
	        	try {
				
			        	if(MyArrList.get(position).get("cardtype").equals(NameCat[i]))
			        	{
			        		holder.laycat_color.setBackgroundColor(Color.parseColor(ColorCat[i]));
			     	        holder.laycat_color2.setBackgroundColor(Color.parseColor(ColorCat[i]));
			     	        holder.txt_cat.setTextColor(Color.parseColor(ColorCat[i]));
			     	        holder.txt_cat.setText(NameCat[i]);
			     	        
			        	}
			        	else
			        		Log.e("TG", "Not fond CardType:"+MyArrList.get(position).get("cardtype"));
			        		
	        	} catch (Exception e) {
	        		Log.e("TG","CardType ERROR:"+e.toString());
				}
			        	
			        	i++;
			        	
	        	
	        	
	        }
	        
	       
	        
	        
	        
	        
	        //===============Menu==============
	        holder.img_addbookmark.setOnClickListener(new OnClickListener() {
	             @Override
	             public void onClick(View v) {
	            	 
	             card_id=MyArrList.get(position).get("card_id").toString();
	             title=MyArrList.get(position).get("name").toString();
	             Toast.makeText(activity, "add bookmark :"+card_id+" "+title, 700).show();
	             
	             if(new ConnectInternet(activity).checkInternetConnection());
	             new Load_AddBookmark().execute();
	             
	             }});
	        
	        holder.img_call.setOnClickListener(new OnClickListener() {
	             @Override
	             public void onClick(View v) {
	             Toast.makeText(activity, "call", 700).show();
	             allintent.CallPhone(MyArrList.get(position).get("tel").toString());
	             
	             }});
	        
		    holder.img_compare.setOnClickListener(new OnClickListener() {
	             @Override
	             public void onClick(View v) {
	        
	              	 title=MyArrList.get(position).get("name").toString();
	            	 card_id=MyArrList.get(position).get("card_id").toString();
	            	// Toast.makeText(activity, "add bookmark :"+card_id+" "+title, 700).show();
	            	 
		            
	            	 if(new ConnectInternet(activity).checkInternetConnection());
	            	 new Load_AddToCompare().execute();
	             
	             
	             }});
		    
		    holder.img_map.setOnClickListener(new OnClickListener() {
	             @Override
	             public void onClick(View v) {
	            	 
	            	 
	             Control.Pointers="CardActivity";
	             CardActivity.titlemap= MyArrList.get(position).get("name").toString();
	             CardActivity.latitude= MyArrList.get(position).get("latitude").toString();
	             CardActivity.longitude= MyArrList.get(position).get("longitude").toString();
	            	 
	             Toast.makeText(activity, "Open Map "+MyArrList.get(position).get("name").toString()+" ,"+CardActivity.latitude+", "+CardActivity.longitude, 700).show();
         		 activity.startActivity(new Intent(activity,MapActivity.class));

	            
	             
	             
	             }});
		    
		    holder.img_web.setOnClickListener(new OnClickListener() {
	             @Override
	             public void onClick(View v) {
	            	
	            	 allintent.OpenWeb(MyArrList.get(position).get("web").toString());
	             
	             }});
	        
	        
	        
      } catch (Exception ex){Toast.makeText(activity,ex.toString(),500).show();}
	        
	return vi;
    }
    
    
    public static void initImageLoader(Context context) {
  		// This configuration tuning is custom. You can tune every option, you may tune some of them, 
  		// or you can create default configuration by
  		//  ImageLoaderConfiguration.createDefault(this);
  		// method.
  		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
  		.memoryCacheExtraOptions(480, 800) // default = device screen dimensions
        .threadPoolSize(3) // default
        .threadPriority(Thread.NORM_PRIORITY - 1) // default
        .tasksProcessingOrder(QueueProcessingType.FIFO) // default
        .denyCacheImageMultipleSizesInMemory()
        .memoryCache(new LruMemoryCache(2 * 1024 * 1024))
        .memoryCacheSize(2 * 1024 * 1024)
        .discCacheSize(50 * 1024 * 1024)
        .discCacheFileCount(100)
        .discCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default
        .imageDownloader(new BaseImageDownloader(context)) // default
        .imageDecoder(new BaseImageDecoder(true)) // default
        .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
        .build();
  		// Initialize ImageLoader with configuration.
  		ImageLoader.getInstance().init(config);
  	}
  	
    
  	@SuppressWarnings("unused")
	private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {

		static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());

		@Override
		public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
			if (loadedImage != null) {
				ImageView imageView = (ImageView) view;
				boolean firstDisplay = !displayedImages.contains(imageUri);
				if (firstDisplay) {
					FadeInBitmapDisplayer.animate(imageView, 500);
					displayedImages.add(imageUri);
				}
			}
		}
	}
    
  	
  	
  	
  	
	class Load_AddToCompare extends AsyncTask<Object, Integer, Object> {

		  

		private ProgressDialog mProgressDialog3;
		private String content,images,date,link,result,desc;
		private boolean Cancle=false;
		
		  @Override
		protected void onCancelled() {
			// TODO Auto-generated method stub
			  Cancle=true;
			super.onCancelled();
		}
		@SuppressWarnings("null")
		@Override
		protected Object doInBackground(Object... params) {

			try {
				 ArrayList<String> arrayList_parametor=new ArrayList<String>();
				 ArrayList<String> arrayList_value=new ArrayList<String>();
				
				 arrayList_parametor.add("pageid");
				 arrayList_value.add(Control.page_id);
					
				
				 arrayList_parametor.add("cardid");
				 arrayList_value.add(card_id);
				
				 arrayList_parametor.add("username");
				 arrayList_value.add(Control.UserName);
		
				 
				 String cardname=title.replace(" ","%20");
				 
				 arrayList_parametor.add("cardname");
				 arrayList_value.add(cardname);
				 
				 
				 Log.e("TG","Load_AddToCompare:"+Control.page_id+":"+Control.UserName+":"+card_id+" cardname:"+cardname);
				 
				 
				 SendToBD sd=new SendToBD(activity);
				 String respone=sd.send(
							Control.user, 
							Control.pass, 
							Control.getAPI_AddToCompare(),
							arrayList_parametor,
							arrayList_value);
					
					JSONObject jsonObj;
					jsonObj = new JSONObject(respone);
					
					
					Log.e("tg","desc="+jsonObj.getString("desc"));
				
					desc=jsonObj.getString("desc");
					
					
					
					
				
				 
				} catch (JSONException e) {
					
					e.printStackTrace();
				
				}
			return null;
		}
				

		@Override
		protected void onPreExecute() {

			 //=====================ProgressDialog==========================
			if(mProgressDialog3==null)
			{
		        mProgressDialog3 = new ProgressDialog(activity);
		        mProgressDialog3.setProgressStyle(ProgressDialog.STYLE_SPINNER);         
		        mProgressDialog3.setMessage("Add To Compare....");                       
		    	mProgressDialog3.setCancelable(true);
			}
			
			if(mProgressDialog3!=null)
				mProgressDialog3.show();
			
			
			
			super.onPreExecute();
		}

		@Override
		public void onProgressUpdate(Integer... progress) {

			Log.e("star", "progressupdate");
			
			
		}

		@Override
		protected void onPostExecute(Object result) {
			
			if(!Cancle)
			{
				Toast.makeText(activity, desc, 800).show();

			}
			
		if(mProgressDialog3!=null)
			mProgressDialog3.hide();
		}

	}
	
	class Load_AddBookmark extends AsyncTask<Object, Integer, Object> {

		  

		private ProgressDialog mProgressDialog2;
		private String desc;
		private boolean Cancle=false;
		
		  @Override
		protected void onCancelled() {
			// TODO Auto-generated method stub
			  Cancle=true;
			super.onCancelled();
		}
		@SuppressWarnings("null")
		@Override
		protected Object doInBackground(Object... params) {

			try {
				title=title.replace(" ", "%20");
				JSONObject jsonObj=null;
				jsonObj = new JSONObject(HttpGetJson.GetJson(Control.getAPI_AddTobookmark_Card(card_id,title, Control.UserName),Control.user,Control.pass));
				
			//Log.e("TG",(HttpGetJson.GetJson(Control.getAPI_AddTobookmark(Control.page_id, Control.UserName),Control.user,Control.pass)));

			
		    desc=jsonObj.getString("desc");
		  
		    
		    
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
				 
			return null;
		}

		@Override
		protected void onPreExecute() {

			 //=====================ProgressDialog==========================
			if(mProgressDialog2==null)
			{
		        mProgressDialog2 = new ProgressDialog(activity);
		        mProgressDialog2.setProgressStyle(ProgressDialog.STYLE_SPINNER);         
		        mProgressDialog2.setMessage("Loading......");                       
		    	mProgressDialog2.setCancelable(true);
			}
			
			if(mProgressDialog2!=null)
				mProgressDialog2.show();
			
			
			
			super.onPreExecute();
		}

		@Override
		public void onProgressUpdate(Integer... progress) {

			Log.e("star", "progressupdate");
			
			
		}

		@Override
		protected void onPostExecute(Object result) {
			
			if(!Cancle)
			{
				Toast.makeText(activity, desc, 800).show();

			}
			
		if(mProgressDialog2!=null)
			mProgressDialog2.hide();
		}

	}
	
	
   
    
    
}